<template>
  <view class="profile-container">
    <!-- 状态栏占位 -->
    <view class="status-bar"></view>
    
    <!-- 头部区域 -->
    <view class="header-section">
      <view class="back-button" @click="goBack">
        <text class="back-icon">←</text>
      </view>
    </view>
    
    <!-- 用户头像区域 -->
    <view class="avatar-section">
      <view class="avatar-container" @click="isEditMode ? chooseAvatar() : null">
        <image 
          :src="getAvatarUrl(userInfo?.avatarUrl)" 
          class="avatar-image"
          mode="aspectFill"
          @error="onAvatarError"
        />
        <view v-if="avatarLoadError" class="avatar-placeholder">
          <text class="avatar-text">{{ (userInfo?.UserName || userInfo?.userName || userInfo?.username)?.charAt(0) || 'U' }}</text>
        </view>
        <view v-if="isEditMode" class="avatar-edit-overlay">
          <text class="edit-icon">📷</text>
        </view>
      </view>
      <text class="avatar-hint" v-if="isEditMode">点击更换头像</text>
    </view>
    
    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-section">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
         <!-- 用户信息表单 -->
     <view v-else class="info-section">
       <view class="info-group">
        <text class="info-label">用户名</text>
        <input 
          v-if="isEditMode"
          v-model="editForm.userName"
          class="info-input"
          placeholder="请输入用户名"
        />
        <text v-else class="info-value">{{ userInfo?.UserName || userInfo?.userName || userInfo?.username || '未设置' }}</text>
      </view>
      
      <view class="info-group">
        <text class="info-label">邮箱</text>
        <input 
          v-if="isEditMode"
          v-model="editForm.email"
          class="info-input"
          type="email"
          placeholder="请输入邮箱"
        />
        <text v-else class="info-value">{{ userInfo?.Email || userInfo?.email || '未设置' }}</text>
      </view>
      
             <view class="info-group">
         <text class="info-label">手机号</text>
         <input 
           v-if="isEditMode"
           v-model="editForm.phoneNumber"
           class="info-input"
           type="number"
           placeholder="请输入手机号"
         />
         <text v-else class="info-value">{{ userInfo?.PhoneNumber || userInfo?.phoneNumber || userInfo?.phone || '未设置' }}</text>
       </view>
       
       <view class="info-group">
        <text class="info-label">状态</text>
        <view class="status-badge" :class="getStatusClass(userInfo?.status)">
          <text class="status-text">{{ getStatusText(userInfo?.status) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 错误信息显示 -->
    <view v-if="errorMessage" class="error-section">
      <text class="error-text">{{ errorMessage }}</text>
      <button class="retry-button" @click="loadUserInfo">重试</button>
    </view>
    
         <!-- 操作按钮区域 -->
     <view class="actions-section">
       <button 
         class="action-button change-avatar-btn" 
         @click="chooseAvatar"
       >
         更换头像
       </button>
       
       <button 
         v-if="!isEditMode"
         class="action-button change-password-btn" 
         @click="showChangePasswordModal"
       >
         修改密码
       </button>

       
       <button 
         class="action-button logout-btn" 
         @click="handleLogout"
       >
         退出登录
       </button>
     </view>
    
         <!-- 修改密码弹窗 -->
     <view v-if="showPasswordModal" class="modal-overlay" @click="hideChangePasswordModal">
       <view class="modal-content" @click.stop>
         <view class="modal-header">
           <text class="modal-title">修改密码</text>
           <text class="modal-close" @click="hideChangePasswordModal">×</text>
         </view>
         
         <view class="password-form">
           <view class="input-group">
             <text class="input-label">当前密码</text>
             <input 
               v-model="passwordForm.oldPassword"
               class="password-input"
               type="password"
               placeholder="请输入当前密码"
             />
           </view>
           
           <view class="input-group">
             <text class="input-label">新密码</text>
             <input 
               v-model="passwordForm.newPassword"
               class="password-input"
               type="password"
               placeholder="请输入新密码"
             />
           </view>
           
           <view class="input-group">
             <text class="input-label">确认新密码</text>
             <input 
               v-model="passwordForm.confirmPassword"
               class="password-input"
               type="password"
               placeholder="请再次输入新密码"
             />
           </view>
         </view>
         
         <view class="modal-actions">
           <button class="modal-btn cancel-btn" @click="hideChangePasswordModal">取消</button>
           <button class="modal-btn confirm-btn" @click="handleChangePassword">确认修改</button>
         </view>
       </view>
     </view>
     

   </view>
 </template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useUserStore } from '@/store/user.js'
import { getUserDetail, updateUser, changePassword, uploadUserAvatar, clearAuth } from '@/api/user.js'
import { BASE_URL } from '@/utils/config.js'

const userStore = useUserStore()

// 响应式数据
const isEditMode = ref(false)
const showPasswordModal = ref(false)
const userInfo = ref(null)
const isLoading = ref(false)
const errorMessage = ref('')
const avatarLoadError = ref(false)

// 编辑表单
const editForm = reactive({
  userName: '',
  email: '',
  phoneNumber: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 计算属性
const currentUserId = computed(() => userStore.userInfo?.id || userInfo.value?.id)

// 生命周期
onMounted(() => {
  loadUserInfo()
})

// 加载用户信息
const loadUserInfo = async () => {
  try {
    isLoading.value = true
    
    console.log('开始加载用户信息...')
    console.log('Store中的用户信息:', userStore.userInfo)
    console.log('当前用户ID:', currentUserId.value)
    
    // 优先从store获取，如果没有则从API获取
    if (userStore.userInfo) {
      userInfo.value = userStore.userInfo
      console.log('从Store获取用户信息:', userInfo.value)
    } else if (currentUserId.value) {
      console.log('从API获取用户信息，用户ID:', currentUserId.value)
      const response = await getUserDetail(currentUserId.value)
      console.log('API响应:', response)
      userInfo.value = response.data || response
      userStore.setUserInfo(userInfo.value)
    } else {
      console.log('无法获取用户信息：用户ID不存在')
      // 尝试从本地存储获取
      const localUserInfo = uni.getStorageSync('userInfo')
      if (localUserInfo) {
        userInfo.value = localUserInfo
        userStore.setUserInfo(localUserInfo)
        console.log('从本地存储获取用户信息:', localUserInfo)
      }
    }
    
    // 初始化编辑表单
    initEditForm()
    console.log('编辑表单初始化完成:', editForm)
    
    // 清除错误信息
    errorMessage.value = ''
    avatarLoadError.value = false
    
  } catch (error) {
    console.error('加载用户信息失败:', error)
    errorMessage.value = '加载用户信息失败，请检查网络连接'
    uni.showToast({
      title: '加载用户信息失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 初始化编辑表单
const initEditForm = () => {
  if (userInfo.value) {
    editForm.userName = userInfo.value.UserName || userInfo.value.userName || userInfo.value.username || ''
    editForm.email = userInfo.value.Email || userInfo.value.email || ''
    editForm.phoneNumber = userInfo.value.PhoneNumber || userInfo.value.phoneNumber || userInfo.value.phone || ''
  }
}

// 切换编辑模式
const toggleEditMode = async () => {
  if (isEditMode.value) {
    // 保存模式
    await saveUserInfo()
  } else {
    // 编辑模式
    isEditMode.value = true
    initEditForm()
  }
}

// 保存用户信息
const saveUserInfo = async () => {
  try {
    if (!currentUserId.value) {
      throw new Error('用户ID不存在')
    }
    
    const updateData = {
      UserName: editForm.userName,
      Email: editForm.email,
      PhoneNumber: editForm.phoneNumber
    }
    
    const response = await updateUser(currentUserId.value, updateData)
    
    if (response.data || response.success) {
      // 更新本地数据
      userInfo.value = { ...userInfo.value, ...updateData }
      userStore.setUserInfo(userInfo.value)
      
      uni.showToast({
        title: '保存成功',
        icon: 'success'
      })
      
      isEditMode.value = false
    } else {
      throw new Error('保存失败')
    }
    
  } catch (error) {
    console.error('保存用户信息失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    })
  }
}

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      await uploadAvatar(tempFilePath)
    },
    fail: (error) => {
      console.error('选择头像失败:', error)
      uni.showToast({
        title: '选择头像失败',
        icon: 'none'
      })
    }
  })
}

// 上传头像
const uploadAvatar = async (filePath) => {
  try {
    if (!currentUserId.value) {
      throw new Error('用户ID不存在')
    }
    
    uni.showLoading({ title: '上传中...' })
    
    const response = await uploadUserAvatar(currentUserId.value, filePath)
    
    if (response.data || response.success) {
      // 更新头像URL
      const avatarUrl = response.data?.avatarUrl || response.avatarUrl
      if (avatarUrl) {
        // 确保保存的是文件名，而不是完整URL
        // 如果返回的是完整URL，提取文件名
        let avatarFileName = avatarUrl
        if (avatarUrl.includes('/')) {
          avatarFileName = avatarUrl.split('/').pop()
        }
        // 如果文件名包含查询参数，去掉
        if (avatarFileName.includes('?')) {
          avatarFileName = avatarFileName.split('?')[0]
        }
        
        userInfo.value.avatarUrl = avatarFileName
        userStore.setUserInfo(userInfo.value)
        
        uni.showToast({
          title: '头像上传成功',
          icon: 'success'
        })
      }
    } else {
      throw new Error('上传失败')
    }
    
  } catch (error) {
    console.error('上传头像失败:', error)
    uni.showToast({
      title: '上传头像失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 显示修改密码弹窗
const showChangePasswordModal = () => {
  showPasswordModal.value = true
  // 清空密码表单
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

// 隐藏修改密码弹窗
const hideChangePasswordModal = () => {
  showPasswordModal.value = false
}

// 处理修改密码
const handleChangePassword = async () => {
  try {
    // 验证密码
    if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
      uni.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }
    
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      uni.showToast({
        title: '两次密码输入不一致',
        icon: 'none'
      })
      return
    }
    
    if (passwordForm.newPassword.length < 6) {
      uni.showToast({
        title: '新密码长度不能少于6位',
        icon: 'none'
      })
      return
    }
    
    if (!currentUserId.value) {
      throw new Error('用户ID不存在')
    }
    
    const response = await changePassword(
      currentUserId.value,
      passwordForm.oldPassword,
      passwordForm.newPassword,
      passwordForm.confirmPassword
    )
    
    if (response.data || response.success) {
      uni.showToast({
        title: '密码修改成功',
        icon: 'success'
      })
      
      hideChangePasswordModal()
      
      // 清空密码表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      throw new Error('修改失败')
    }
    
  } catch (error) {
    console.error('修改密码失败:', error)
    uni.showToast({
      title: error.message || '修改密码失败',
      icon: 'none'
    })
  }
}

// 处理深度思考
const handleDeepThinking = () => {
  uni.showModal({
    title: '深度思考',
    content: '这是一个深度思考功能，您想要进行什么类型的思考？',
    showCancel: true,
    cancelText: '取消',
    confirmText: '开始思考',
    success: (res) => {
      if (res.confirm) {
        // 这里可以添加深度思考的具体逻辑
        uni.showToast({
          title: '开始深度思考...',
          icon: 'success'
        })
        
        // 可以跳转到专门的思考页面或执行其他逻辑
        // uni.navigateTo({
        //   url: '/pages/deep-thinking/deep-thinking'
        // })
      }
    }
  })
}

// 处理退出登录
const handleLogout = () => {
  uni.showModal({
    title: '确认退出',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除用户信息
        userStore.clearUserInfo()
        clearAuth()
        
        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/Login/login'
        })
      }
    }
  })
}

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    fail: () => {
      // 如果没有上一页，则跳转到主页
      uni.navigateTo({
        url: '/pages/index/index'
      })
    }
  })
}

// 跳转到问答页面
const goToQuestions = () => {
  uni.navigateTo({
    url: '/pages/Questions/questions'
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    return dateString
  }
}

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 'active':
      return 'status-active'
    case 'inactive':
      return 'status-inactive'
    case 'suspended':
      return 'status-suspended'
    default:
      return 'status-unknown'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'active':
      return '正常'
    case 'inactive':
      return '未激活'
    case 'suspended':
      return '已暂停'
    default:
      return '未知'
  }
}

// 头像加载错误处理
const onAvatarError = () => {
  avatarLoadError.value = true
}

// 获取头像完整URL
const getAvatarUrl = (avatarUrl) => {
  if (!avatarUrl) {
    // 如果没有头像，返回默认头像
    return BASE_URL + '/users/avatar-file/default-avatar.png'
  }
  
  // 如果已经是完整URL，直接返回
  if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
    return avatarUrl
  }
  
  // 如果是相对路径，拼接基础URL
  if (avatarUrl.startsWith('/')) {
    return BASE_URL + avatarUrl
  }
  
  // 如果是文件名，使用头像文件路径前缀
  // 例如: avatar123.jpg -> http://api-rag.monkeymeerkat.cn/api/users/avatar-file/avatar123.jpg
  return BASE_URL + '/users/avatar-file/' + avatarUrl
}
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 0;
  position: relative;
}

.status-bar {
  height: calc(60rpx + env(safe-area-inset-top, 0px));
}

.header-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 40rpx;
  background: white;
  border-bottom: 1rpx solid #e9ecef;
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 40rpx;
  color: #333;
}



.edit-text {
  color: white;
  font-size: 28rpx;
  font-weight: 500;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 40rpx;
  background: white;
  margin-bottom: 20rpx;
}

.avatar-container {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  font-size: 60rpx;
  color: white;
  font-weight: bold;
}

.avatar-edit-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-icon {
  font-size: 40rpx;
  color: white;
}

.avatar-hint {
  font-size: 24rpx;
  color: #666;
}

.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  background: white;
  margin-bottom: 20rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
  background: white;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
  border: 1rpx solid #f8d7da;
}

.error-text {
  font-size: 28rpx;
  color: #721c24;
  margin-bottom: 20rpx;
  text-align: center;
}

.retry-button {
  padding: 16rpx 32rpx;
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 12rpx;
  font-size: 28rpx;
}

.info-section {
  background: white;
  margin-bottom: 20rpx;
}

.info-group {
  display: flex;
  align-items: center;
  padding: 40rpx;
  border-bottom: 1rpx solid #f1f3f4;
}

.info-group:last-child {
  border-bottom: none;
}

.info-label {
  width: 160rpx;
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.info-input {
  flex: 1;
  font-size: 30rpx;
  color: #333;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
}

.info-value {
  flex: 1;
  font-size: 30rpx;
  color: #333;
}

.info-value-disabled {
  color: #999;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.status-active {
  background: #d4edda;
  color: #155724;
}

.status-inactive {
  background: #fff3cd;
  color: #856404;
}

.status-suspended {
  background: #f8d7da;
  color: #721c24;
}

.status-unknown {
  background: #e2e3e5;
  color: #383d41;
}

.status-text {
  font-weight: 500;
}

.actions-section {
  padding: 40rpx;
}

.action-button {
  width: 100%;
  height: 90rpx;
  border: none;
  border-radius: 20rpx;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
  transition: all 0.3s ease;
}

.change-avatar-btn {
  background: #4CAF50;
  color: white;
}

.change-avatar-btn:active {
  background: #388e3c;
  transform: scale(0.98);
}

.change-password-btn {
  background: #667eea;
  color: white;
}

.change-password-btn:active {
  background: #5a6fd8;
  transform: scale(0.98);
}

.deep-thinking-btn {
  background: #28a745;
  color: white;
}

.deep-thinking-btn:active {
  background: #218838;
  transform: scale(0.98);
}

.logout-btn {
  background: #dc3545;
  color: white;
}

.logout-btn:active {
  background: #c82333;
  transform: scale(0.98);
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 80%;
  max-width: 600rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx;
  border-bottom: 1rpx solid #e9ecef;
}

.modal-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.modal-close {
  font-size: 40rpx;
  color: #999;
  padding: 10rpx;
}

.password-form {
  padding: 40rpx;
}

.input-group {
  margin-bottom: 30rpx;
}

.input-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.password-input {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  border: 1rpx solid #e9ecef;
  border-radius: 12rpx;
  font-size: 28rpx;
  background: #f8f9fa;
}

.modal-actions {
  display: flex;
  padding: 40rpx;
  gap: 20rpx;
}

.modal-btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.cancel-btn {
  background: #f8f9fa;
  color: #666;
}

.confirm-btn {
  background: #667eea;
  color: white;
}

/* 浮动箭头按钮样式 */
.floating-arrow-btn {
  position: absolute;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  background: #667eea;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);
  z-index: 100;
}

.floating-arrow-btn:active {
  background: #5a6fd8;
  transform: scale(0.95);
}


</style>
